package com.ruoyi.web.core;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public class SentenceService {

    public void apiSentence() {
        Optional.ofNullable(HttpUtil.get("https://v1.jinrishici.com/all.json", 3000))
                .map(JSONUtil::parseObj)
                .ifPresent(jo -> {
                    System.out.println(StrUtil.format("{} -- 《{}》 {}",
                            jo.getStr("content"),
                            jo.getStr("origin"),
                            jo.getStr("author")));
                });
    }

    /*String token = "RgU1rBKtLym/MhhYIXs42WNoqLyZeXY3EkAcDNrcfKkzj8ILIsAP1Hx0NGhdOO1I";

    public String apiToken() {
        return Optional.ofNullable(HttpUtil.get("https://v2.jinrishici.com/token", 3000))
                .map(JSONUtil::parseObj)
                .map(o -> o.getStr("data"))
                .orElseThrow(() -> new RuntimeException("调用今日诗词接口失败"));
    }

    public void apiSentence() {
        try {
            if (StrUtil.isEmpty(token)) {
                token = apiToken();
            }
            String res = new HttpRequest("https://v2.jinrishici.com/sentence")
                    .header("X-User-Token", token)
                    .setMethod(Method.GET)
                    .timeout(3000)
                    .execute().body();
            JSONObject jo = JSONUtil.parseObj(res);
            if (!"success".equals(jo.get("status"))) {
                return;
            }

            JSONObject data = jo.getJSONObject("data");
            JSONObject origin = data.getJSONObject("origin");
            System.out.println(StrUtil.format("{} -- 《{}》 {} 【{}】",
                    data.getStr("content"),
                    origin.getStr("title"),
                    origin.getStr("author"),
                    origin.getStr("dynasty")));
        } catch (Exception e) {
            log.warn("{}", e.getMessage());
        }
    }*/
}
